#include <assert.h>
#include <stdio.h>
#include<string.h>
#include "parse.h"

void parse_cmd(char *line, struct cmd * cmd)
{
    char *token,buf[100];
    int i=0,argc=0;
    strcpy(buf,line);
    token=strtok(buf," ");
    cmd->argv[0]=strdup(token);
    i++;
    while(token!=NULL)
    {
        token=strtok(NULL," ");
        if(token!=NULL){
            cmd->argv[i]=strdup(token);
            i++;
        }
    }
    cmd->argv[i]=NULL;
    for(i=0;cmd->argv[i]!=NULL;i++)
    {
        argc++;
    }
    cmd->argc=argc;
    cmd->input=NULL;
    cmd->output=NULL;

    for(i=0;cmd->argv[i]!=NULL;i++)
    {
       if(cmd->argv[i][0] == '<')
        {
            int j = 1;
            for (; cmd->argv[i][j-1] != '\0'; j++)
            {
                cmd->argv[i][j - 1] = cmd->argv[i][j];
            }
            cmd->input = cmd->argv[i];
            cmd->argv[i] = NULL;
        }
        else if(cmd->argv[i][0] == '>')
        {
            int j = 1;
            for (; cmd->argv[i][j-1] != '\0'; j++)
            {
                cmd->argv[i][j - 1] = cmd->argv[i][j];
            }
            cmd->output = cmd->argv[i];
            cmd->argv[i] = NULL;
        }
    }
}

void dump_cmd(struct cmd *cmd)
{
        printf("argc = %d\n", cmd->argc);
        int i;
        for (i = 0; i < cmd->argc; i++) {
             printf("argv[%d] = (%s)\n", i, cmd->argv[i]);
        }

        char *input = cmd->input ? cmd->input : "NULL";
        printf("input = (%s)\n", input);

        char *output = cmd->output ? cmd->output : "NULL";
        printf("output = (%s)\n", output);
}
